package cn.lzh.tool;

import cn.lzh.entity.MyUser;
import cn.lzh.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
public class Token {
    @Autowired
    UserMapper userMapper;
    private static UserMapper userDao2 = null;
    private static Logger log = LoggerFactory.getLogger("Token");


    public static String getAccount() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("principal=" + principal);
        if (principal == null) {
            return null;
        } else {
            return principal instanceof UserDetails ? ((UserDetails)principal).getUsername() : String.valueOf(principal);
        }
    }

    @PostConstruct
    public void init() {
        userDao2 = this.userMapper;
    }

    public static int getUid() {
        String account = "";
        account = getAccount();
        log.info("accpunt=" + account);
        if (account != null && account.length() >= 1) {
            MyUser u = userDao2.findByAccount(account);
            log.info("User=" + u);
            return u == null ? -1 : u.getId();
        } else {
            return -1;
        }
    }

    public static MyUser getUser() {
        String account = "";
        account = getAccount();
        if (account != null && account.length() >= 1) {
            System.out.println("getUser account=" + account);
            MyUser u = userDao2.findByAccount(account);
            return u;
        } else {
            return null;
        }
    }
}
